package cn.lg.soar.system.general.controller;


import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import cn.lg.soar.common.model.HttpResult;
import cn.lg.soar.common.util.FileUtil;
import cn.lg.soar.common.util.IpUtil;
import cn.lg.soar.common.util.ParameterUtil;
import cn.lg.soar.common.util.data.RandomUtil;
import cn.lg.soar.core.api.IResourceApi;
import cn.lg.soar.mvc.aspect.idempotent.IdempotentService;
import cn.lg.soar.system.api.constant.ModuleConst;
import cn.lg.soar.system.general.service.IPublicService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.util.Set;

/**
 * @author luguoxiang
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
@RefreshScope
@Api(tags = {"公共接口"})
@RestController
@RequestMapping(ModuleConst.MODULE_NAME + "/public")
public class PublicController {

    @Value("${lg.general.biz-type.enabled: false}")
    private boolean enabled;
    @Value("${lg.general.biz-type.blacklist: login}")
    private Set<String> blacklist;

    @Autowired
    private IPublicService publicService;
    @Autowired
    private IdempotentService idempotentService;
    @Autowired
    private IResourceApi resourceApi;

    @ApiOperation("获取动态公钥")
    @GetMapping(value = "rsaDynamicPKI", name = "获取动态公钥")
    public HttpResult<String> rsaDynamicPKI(@RequestParam String bizType) {
        ParameterUtil.isTrue(!enabled || this.blacklist.contains(bizType), "业务类型不在白名单内");
        return HttpResult.data(this.publicService.getRSAPublicKeyB64(bizType));
    }

    @ApiOperation("获取SM2动态公钥")
    @GetMapping(value = "sm2DynamicPKI", name = "获取SM2动态公钥")
    public HttpResult<String> sm2DynamicPKI(@RequestParam String bizType) {
        ParameterUtil.isTrue(!enabled || this.blacklist.contains(bizType), "业务类型不在白名单内");
        return HttpResult.data(this.publicService.getSM2PublicKeyHex(bizType));
    }

    @ApiOperation("获取图片验证码")
    @GetMapping(value = "captcha", name = "获取验证码图片")
    public String captcha(
            @RequestParam String bizType,
            @ApiParam(name="toBase64",value="为true时返回base64数据,默认返回图片")
            @RequestParam(required = false, defaultValue = "false") Boolean toBase64
    ) {
        ParameterUtil.isTrue(this.blacklist.contains(bizType), "业务类型不在白名单内");
        return this.publicService.getCaptcha(bizType, toBase64);
    }

    @ApiOperation("获取幂等token")
    @GetMapping(value = "idempotentToken", name = "获取幂等token")
    public HttpResult<String> idempotentToken(HttpServletRequest request) {
        int ip = IpUtil.getRemoteIpInt(request);
        return HttpResult.data(this.idempotentService.getTokenByIp(ip));
    }

    @ApiOperation("获取uuid")
    @GetMapping(value = "uuid", name = "获取uuid")
    public HttpResult<String> uuid() {
        return HttpResult.data(RandomUtil.uuid());
    }

    @ApiOperation("生成二维码")
    @GetMapping(value = "genQrcode", name = "生成二维码")
    public HttpResult<String> genQrcode(
            @RequestParam String content,
            @RequestParam(required = false, defaultValue = "300") int width,
            @RequestParam(required = false, defaultValue = "FFFFFF") String backColor,
            @RequestParam(required = false, defaultValue = "000000") String foreColor,
            @RequestParam(required = false, defaultValue = "1") int margin,
            @RequestParam(required = false, defaultValue = "false") Boolean toBase64,
            HttpServletResponse resp
    ) throws IOException {
        QrConfig config = new QrConfig(width, width);
        config.setBackColor(Integer.parseInt(backColor, 16));
        config.setForeColor(Integer.parseInt(foreColor, 16));
        config.setMargin(margin);
        BufferedImage bufferedImage = QrCodeUtil.generate(content, config);
        if (toBase64) {
            return HttpResult.data(FileUtil.bufferedImageToBase64(bufferedImage));
        }
        FileUtil.bufferedImageToOut(bufferedImage, resp);
        return null;
    }

    @ApiOperation("二维码解码")
    @PostMapping(value = "decodeQrcode", name = "二维码解码")
    public HttpResult<String> decodeQrcode(MultipartFile file) {
        try (InputStream inputStream = file.getInputStream()) {
            return HttpResult.data(QrCodeUtil.decode(inputStream));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @ApiOperation("获取枚举信息")
    @GetMapping(value = "enums", name = "获取枚举信息")
    public HttpResult<?> get(@ApiParam("枚举类型名称") String[] names) {
        return HttpResult.data(resourceApi.getEnums(names == null ? new String[0] : names));
    }

}
